'use strict';
var ksrCustomerAcct = angular.module('ksrCustomerAcct',[
    'ngCookies'
    ,'ngRoute'
    ,'ui.bootstrap'
    ,'ksrCustomerAcctControllers'
    ,'ksr.filters'
    ,'ksr.services'
    ,'ksr.directives'
    ,'ksrFileupload'
    //,'KSR.filters'
    //'KSR.services'
]);

ksrCustomerAcct.config(['$routeProvider','$locationProvider',
    function($routeProvider,$locationProvider){
		$routeProvider.
		when("/overview",{
			templateUrl:'/ksr/partials/customer/account-overview.htm'
			,controller:"acctOverviewCtrl"
		}).
		when("/edit-customer-profile",{
			templateUrl:'/ksr/partials/customer/customer-profile.htm'
				,controller:"customerProfileCtrl"
		}).
		when("/change-password",{
			templateUrl:'/ksr/partials/change-password.htm'
			,controller:"changePasswordCtrl"
		}).
		when("/manage-photos/",{
			templateUrl:'/ksr/partials/customer/manage-photos.htm'
				,controller:"customerManagePhotoCtrl"
		}).
		when("/manage-reviews/",{
			templateUrl:'/ksr/partials/customer/manage-reviews.htm'
				,controller:"customerManageReviewCtrl"
		}).
		when("/manage-subscriptions/",{
			templateUrl:'/ksr/partials/customer/manage-event-subscriptions.htm'
				,controller:"customerManageSubscriptionCtrl"
		}).
		when("/customer-photos/:id",{
			templateUrl:'/ksr/partials/fileupload.htm'
				,controller:"customerPhotoCtrl"
		}).
		when("/customer-reviews/:id",{
			templateUrl:'/ksr/partials/customer/reviews.htm'
				,controller:"customerReviewCtrl"
		}).
		when("/customer-subscription/:id",{
			templateUrl:'/ksr/partials/customer/event-subscription.htm'
				,controller:"customerEventScriptionCtrl"
		}).
		otherwise({
			redirectTo:'/overview'
		});
	}
]);

/*controllers*/
var ksrCustomerAcctControllers = angular.module("ksrCustomerAcctControllers",[])
ksrCustomerAcctControllers.controller('acctOverviewCtrl', ['$scope','ksrCacheSvc',
	 function($scope, ksrCacheSvc) {
	   console.log("acctOverviewCtrl");
	   $scope.breadcrumbs=[
	                  	{"name":"Account","url":"#/overview"}
	                  	,{"name":"overview","url":""}
	                ];
	  
 }]);
ksrCustomerAcctControllers.controller('customerManagePhotoCtrl', ['$scope','ksrCacheSvc',
	 function($scope, ksrCacheSvc) {
	   console.log("customerManagePhotoCtrl");
	   $scope.breadcrumbs=[
	                  	{"name":"Account","url":"#/overview"}
	                  	,{"name":"Manage Photos","url":""}
	                ];
	   ksrCacheSvc.get("customer",false).then(function(data){
	    	$scope.customer = data;
	    })
	    ksrCacheSvc.get("baseUrl",true).then(function(data){
	    	$scope.baseUrl = data.baseUrl;
	    })
	  
 }]);

ksrCustomerAcctControllers.controller('customerManageReviewCtrl', ['$scope','ksrCacheSvc',
	 function($scope, ksrCacheSvc) {
	   console.log("customerManageReviewCtrl");
	   $scope.breadcrumbs=[
	                  	{"name":"Account","url":"#/overview"}
	                  	,{"name":"Manage reviews","url":""}
	                ];
	   ksrCacheSvc.get("customer",true).then(function(data){
	    	$scope.customer = data;
	    	ksrCacheSvc.get("customerReviewList",false,{id:data.id,rating:0}).then(function(data){
	    		$scope.reviewList = data;
	    		$scope.reviewNumbers=data.rating100.length+","+data.rating80.length+","+data.rating60.length+","+data.rating40.length+","+data.rating20.length;
	    		$scope.reviewCount=data.rating100.length+data.rating80.length+data.rating60.length+data.rating40.length+data.rating20.length;
	    		console.log("success to retrieve the reviewList");
	    	},function(err){
	    		console.error("fail to retrieve the reviewList");
	    	})
	    })
 }]);

ksrCustomerAcctControllers.controller('customerManageSubscriptionCtrl', ['$scope','$modal','$rootScope','ksrCacheSvc','jsonSvc',
	 function($scope,$modal,$rootScope, ksrCacheSvc,jsonSvc) {
	   console.log("customerManageSubscriptionCtrl");
	   $scope.breadcrumbs=[
	                  	{"name":"Account","url":"#/overview"}
	                  	,{"name":"Manage Event Subscriptions","url":""}
	                ];
	   ksrCacheSvc.get("customer",true).then(function(data){
	    	$scope.customer = data;
	    	ksrCacheSvc.get("eventSubscriptionList",false,{id:data.id}).then(function(data){
	    		$scope.subscriptionList = data;
	    		console.log("success to retrieve the event subscription list");
	    	},function(err){
	    		console.error("fail to retrieve the event subscription list");
	    	})
	    })
	   		var modalInstance;
	        $scope.cancelSubscription=function(subIdx){
	         	// $modal.open();
	     		modalInstance = $modal.open({templateUrl: '/ksr/partials/confirmModal.htm'});
			    $rootScope.description = "undescribe the subscription";
			    $rootScope.yes = function () {
			        modalInstance.close("yes");
			    };
			    $rootScope.no = function () {
			        modalInstance.dismiss('cancel');
			    };

	    	modalInstance.result.then(function () {
				console.log("cancel subscription,idx="+subIdx);
				jsonSvc.removeItemBy({entityType:"customer",type:"event-subscription"},$scope.subscriptionList[subIdx]).$promise.then(function(data){
					if (data.status==="ok"){
						console.log("unscribe subscription successfully");
						$scope.subscriptionList.splice(subIdx,1);
					} else {
						console.error("unscribe subscription! Error:"+data.errMsg);
						$scope.alerts.push({type:'danger', msg:$sce.trustAsHtml('Fail to unscribe subscription! Please try again later!')});
					}
				});
			    }, function () {
			      console.log('user cancel the unscribe action! idx='+subIdx);
			    });  
		    }
 }]);

ksrCustomerAcctControllers.controller('customerProfileCtrl', ['$scope','$location','$window','ksrCacheSvc','jsonSvc',
    function($scope,$location,$window,ksrCacheSvc,jsonSvc) {
	console.log("businessProfileCtrl");
	$scope.breadcrumbs=[
	                    {"name":"Account","url":"#/overview"}
	                    ,{"name":"profile","url":""}
	                    ];

		ksrCacheSvc.get("customer",true).then(function(data){
	    	if (data.id){ 
				$scope.title = "Edit customer profile";
				$scope.mode="edit";
				$scope.breadcrumbs=[{"name":"Account settings","url":"#/overview"},{"name":"profile","url":""}];
	    		$scope.customer = data;
	    	} else {
	    		$scope.title = "Create your customer profile";
				$scope.mode="create";
				$scope.customer = {categories:[]};
	    	}
	    	
	    },function(err){

	    })  ; 

	$scope.submit = function(){
		jsonSvc.saveItem({entityType:"customer",type:"profile"},$scope.customer).$promise.then(function(data){
			console.log("udpate customer status:"+data.status);
			if ($scope.mode==="edit"){
				$location.path("#/overview");
			} else {
				$window.location.href="/ksr/customer/profile.html";
			}
		});
	}
	
}]);
ksrCustomerAcctControllers.controller('changePasswordCtrl', ['$scope', '$location','jsonSvc',
                                                             function($scope,$location,jsonSvc) {
	console.log("changePasswordCtrl");
	$scope.breadcrumbs=[
	                    {"name":"Account","url":"#/overview"}
	                    ,{"name":"password","url":""}
	                    ];
	$scope.pwdObj = {}
	$scope.submit = function(){
		jsonSvc.changePassword({entityType:"customer"},$scope.pwdObj).$promise.then(function(data){
			if (data.status === "ok"){
				console.log("udpate password successfully");
				$location.path("#/overview");
			} else {
				$scope.errMsg = data.status;
			}
		});
	}	
	
}]);

ksrCustomerAcctControllers.controller('customerPhotoCtrl', ['$scope','$controller', '$http','$routeParams',
                                                     function($scope, $controller,$http,$routeParams) {
	console.log("customerPhotoCtrl");
	$scope.breadcrumbs=[
	                    {"name":"Account","url":"#/overview"}
	                    ,{"name":"Manage photos","url":"#/manage-photos"}
	                    ,{"name":"Add or remove photos","url":""}
	                    ];

	 $routeParams.id=$routeParams.id||"customer";
    $controller("ksrFileUploadController", {
        $scope: $scope,
        $http:$http,
        $routeParams:$routeParams
    });
	
}]);
ksrCustomerAcctControllers.controller('customerReviewCtrl', ['$scope','$routeParams','ksrCacheSvc',
	 function($scope,$routeParams,ksrCacheSvc) {
	   console.log("customerReviewCtrl");
	   $scope.breadcrumbs=[
	                  	{"name":"Account","url":"#/overview"}
	                  	,{"name":"Manage reviews","url":"#/manage-reviews"}
	                  	,{"name":"my reviews","url":""}
	                ];

			ksrCacheSvc.get("customerReviewList",false,{id:$routeParams.id}).then(function(data){
	    		$scope.reviewList = data;
	    		console.log("success to retrieve the reviewList");
	    	},function(err){
	    		console.error("fail to retrieve the reviewList");
	    	})

	  
 }]);
ksrCustomerAcctControllers.controller('customerEventScriptionCtrl', ['$scope','$routeParams','ksrCacheSvc',
	 function($scope,$routeParams,ksrCacheSvc) {
	   console.log("customerEventScriptionCtrl");
	   $scope.breadcrumbs=[
	                  	{"name":"Account","url":"#/overview"}
	                  	,{"name":"Manage Event Subscriptions","url":"#/manage-subscriptions"}
	                  	,{"name":"my subscription","url":""}
	                ];
			ksrCacheSvc.getItemById($routeParams.id,"eventSubscriptionList",true).then(function(data){
		   		$scope.subscription = data;
		   })
	    
	      $scope.selectAddress=function(addressId){
	      	console.log("select address:"+addressId);
	      	angular.forEach($scope.subscription.eventSchedule.eventAddresses, function(address){
	      		if (address.id===addressId)
	      			$scope.subscription.address=address;
	      	})
	      }
	    	

	  
 }]);
